<template>
  <div>
    <ul class="nav">
      <li>全部({{allnum}})</li>
      <li>降价({{ list.length }})</li>
      <li>常卖</li>
      <li>分类</li>
    </ul>
    <van-empty
        v-if="list.length == 0"
        description="购物车空空，快去购物吧！"
      />
    <div class="item-box" v-for="(item, index) in list" :key="item.id">
      <div class="item">
        <van-checkbox
          v-model="item.checked"
          shape="square"
          @click="changeOne(index)"
        ></van-checkbox>
      </div>
      <div class="item-right">
        <van-card
          :price="item.price.toFixed(2)"
          :title="item.goodsname"
          :thumb="$pre + item.img"
        >
          <template #tags>
            <van-button type="danger" class="deg" @click="del(item.id)"
              >删除</van-button
            >
          </template>
          <template #footer>
            <van-stepper
              v-model="item.num"
              @plus="plus(item.id)"
              @minus="minus(item.id)"
            />
          </template>
        </van-card>
      </div>
    </div>
    <div class="footer">
      <van-submit-bar
        :price="allPrice * 100"
        button-text="提交订单"
        @click="onSubmit"
        @submit="submit"
      >
        <van-checkbox v-model="checked" @click="checkAll">全选</van-checkbox>
      </van-submit-bar>
    </div>
  </div>
</template>

<script>
import { reqCartlist, reqShopDel, reqShopUpdate } from "../../http/http";
import { Dialog, Toast } from "vant";
export default {
  data() {
    return {
      list: [],
      checked: false,
    };
  },
  computed: {
    // 9总价
    allPrice() {
      return this.list.reduce(
        (val, item) => (item.checked ? (val += item.price * item.num) : val),
        0
      );
    },
    //总数
    allnum(){
       return this.list.reduce(
        (val, item) => (val += item.num),
        0
      );
    }
  },
  methods: {
    onSubmit() {
      console.log(1);
    },
    init() {
      reqCartlist({
        uid: JSON.parse(localStorage.getItem("user")).uid,
      }).then((res) => {
        // 5.4打开开关，方便下一次请求
        if (res.data.code == 200) {
          let arr = res.data.list ? res.data.list : [];
          // 给每条数据加了一个checked状态，代表选中还是未选中

          // 10.arr是刚请回来的数据，this.list是上一次的列表数据. arr中的数据的checked应该是list对应的数据的chekced
          // arr=[{id:1},{id:2},{id:3}]
          // list=[{id:1,checked:true},{id:2,checked:false}]
          arr.forEach((item) => {
            let obj = this.list.find((i) => i.id == item.id);
            item.checked = obj ? obj.checked : false;
          });
          this.list = arr;
        }
      });
    },
    del(id) {
      Dialog.confirm({
        title: "删除提示",
        message: "你确定要删除吗？",
      })
        .then(() => {
          //删除请求
          reqShopDel({
            id: id,
          }).then((res) => {
            if (res.data.code == 200) {
              //弹成功
              Toast(res.data.msg);
              //请列表
              this.init();
            }
          });
        })
        .catch(() => {
          // on cancel
        });
    },
    //全选
    checkAll() {
      console.log(this.checked);
      //所有的checked都可全选一样
      this.list.forEach((item) => {
        item.checked = this.checked;
        console.log(item.checked);
      });
    },
    //切换一个
    changeOne(index) {
      // 切换自己的checked
      // this.list[index].checked = this.list[index].checked;
      //全选
      this.checked = this.list.every((item) => item.checked);
    },
    //加数量
    plus(id) {
      reqShopUpdate({
        id: id,
        type: 2,
      }).then((res) => {
        if (res.data.code == 200) {
          //弹成功
          Toast(res.data.msg);
          //取列表
          this.init();
        }
      });
    },
    //减少
    minus(id) {
      reqShopUpdate({
        id: id,
        type: 1,
      }).then((res) => {
        if (res.data.code == 200) {
          //弹成功
          Toast(res.data.msg);
          //取列表
          this.init();
        }
      });
    },
    //提交
    submit(){
      if(this.list.every((item) => item.checked==false))
      {
        Toast('请先选择要购买的商品')
        return
      }
      //确认订单的数据先存起来
      // countmoney： 总价 countnumber：总数量 idstr:购物车
      let idstr=this.list.reduce(
          (val, item) => (item.checked ? (val += item.id+",") : val),
          ""
        )

      let d = {
        countmoney: this.allPrice,
        countnumber: this.list.reduce(
          (val, item) => (item.checked ? (val += item.num) : val),
          0
        ),
        idstr: idstr.slice(0,idstr.length-1),
      };
      sessionStorage.setItem("d",JSON.stringify(d))
      //前往订单
      this.$router.push("/order")
    }
  },
  mounted() {
    this.init();
  },
};
</script>

<style scoped lang="less">
@import "../../less/index.less";
.nav {
  line-height: @header-nav;
  height: @header-nav;
  text-align: center;
  display: flex;
  color: @while;
  background: @primary;
}
.nav li {
  flex: 1;
}
.footer {
  overflow: hidden;
}
.van-submit-bar__bar {
  margin-bottom: @foot-button;
}
.item-box {
  display: flex;
}
.item {
  width: 15%;
}
.van-checkbox {
  height: 100%;
  align-items: center !important; //垂直居中
  justify-content: center !important; //水平居中
}
.item-right {
  flex: 1;
}
//删除
.deg {
  float: right;
}
</style>
